<template>
  <div class="pharmacy-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"
            stroke-linejoin="round" />
        </svg>
      </div>
      <div class="title">Anfine大药房123</div>
    </div>

    <!-- 二级菜单 -->
    <div class="category-tabs">
      <div v-for="category in categories" :key="category.id" class="tab-item"
        :class="{ active: activeCategory === category.id }" @click="selectCategory(category.id)">
        {{ category.name }}
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧三级菜单 -->
      <div class="left-sidebar">
        <div v-for="subCategory in currentSubCategories" :key="subCategory.id" class="sub-category-item"
          :class="{ active: activeSubCategory === subCategory.id }" @click="selectSubCategory(subCategory.id)">
          {{ subCategory.name }}
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <!-- 健康服务标题 -->
        <div class="service-header">
          <h3>健康服务</h3>
        </div>

        <!-- 商品列表 -->
        <div class="product-list">
          <div v-for="product in currentProducts" :key="product.id" class="product-item"
            @click="selectProduct(product)">
            <div class="product-image">
              <img :src="product.image" :alt="product.name" />
            </div>
            <div class="product-info">
              <div class="product-brand">{{ product.brand }}</div>
              <div class="product-name">{{ product.name }}</div>
              <div class="product-price">¥ {{ product.price }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
import { useImage } from '@/hooks';
import { useRouterPush } from '@/composables';
import { useNurseGoods, useDict } from '@/service';
// import { useNurseOrders, useDict } from '@/service';
import Taro, { hideLoading, showLoading, showToast, usePullDownRefresh, stopPullDownRefresh } from '@tarojs/taro';

import good from './good.vue';
import { categories as categoriesData, products as productsData } from './shop'

// 药品分类数据（3级结构）
const categories = ref(categoriesData)
const products = ref(productsData)

// 当前选中的分类
const activeCategory = ref(3) // 默认选中中药饮片
const activeSubCategory = ref(31) // 默认选中消化道分类

// 计算当前二级分类
const currentSubCategories = computed(() => {
  const category = categories.value.find(cat => cat.id === activeCategory.value)
  return category ? category.children : []
})

// 计算当前商品列表
const currentProducts = computed(() => {
  const subCategory = currentSubCategories.value.find(sub => sub.id === activeSubCategory.value)
  if (!subCategory) return []

  // 获取所有三级分类的商品ID
  let productIds = []
  subCategory.children.forEach(child => {
    productIds = [...productIds, ...child.products]
  })

  // 根据商品ID筛选商品
  return products.value.filter(product => productIds.includes(product.id))
})

// 方法
const goBack = () => {
  // 返回上一页
}

const selectCategory = (categoryId) => {
  activeCategory.value = categoryId
  // 自动选择第一个子分类
  const category = categories.value.find(cat => cat.id === categoryId)
  if (category && category.children.length > 0) {
    activeSubCategory.value = category.children[0].id
  }
}

const selectSubCategory = (subCategoryId) => {
  activeSubCategory.value = subCategoryId
}

const selectProduct = (product) => {
  // 选择商品

  // 将商品信息保存到本地缓存
  try {
    Taro.setStorageSync('selectedProduct', product)
    // 商品信息已保存到缓存

    // 跳转到商品详情页
    Taro.navigateTo({
      url: '/pages/product-detail/index'
    })
  } catch (error) {
    // 保存商品信息失败
    Taro.showToast({
      title: '保存商品信息失败',
      icon: 'none'
    })
  }
}

const { getDict } = useDict();

const props = defineProps({
  hospital: {
    type: String,
    required: true
  }
});
const tabData = ref([])

usePullDownRefresh(() => {
  getData();
  stopPullDownRefresh();
});

onMounted(async () => {
  const res = await getDict("shop_type");//nurse_type shop_type
  // 大药房类型 res
  tabData.value = res
  modelValue.value = res[0].itemValue
})

const list = ref<any>([]);

const { getShopGoodsList, loadTreeChildrenNew, loadShopTreeChildren } = useNurseGoods();

const modelValue = ref(0);

const select = ref('');

const { toGoodsDetail } = useRouterPush();

const toDetail = (item: any) => {
  // toDetail
  toGoodsDetail({
    id: item.id,
    pic: item.pic,
    pname: item.goods_name,
    unit: item.unit,
    nurseType: modelValue.value,
    goods_type: '0',
    nurseTypeText: item.goods_name
  });
};

function buildTree(records: any[]) {
  const map = {};
  const roots = [];

  // First create a map of all items by their id
  records.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  // Then build the tree by assigning children to their parents
  records.forEach(item => {
    const parent = map[item.pid];
    if (parent) {
      parent.children.push(map[item.id]);
    } else if (item.pid === "0") {
      roots.push(map[item.id]);
    }
  });

  return roots;
}

const records = [
  {
    "id": "1933675891139428353",
    "pid": "0",
    "hasChild": "1",
    "typeName": "消化道和代谢方面的药物",
    // ... other fields
  },
  {
    "id": "1933676035507372033",
    "pid": "1933675891139428353",
    "hasChild": "1",
    "typeName": "健康服务",
    // ... other fields
  },
  {
    "id": "1933677950026792961",
    "pid": "1933676035507372033",
    "hasChild": "0",
    "typeName": "感冒灵",
    // ... other fields
  }
];


const getData = async () => {
  // modelValue.value
  const id = tabData.value[modelValue.value].itemValue;
  const { error, success } = await loadShopTreeChildren({ goodsType: id, pid: '' });
  // success
  // showLoading({ title: '正在请求...' });
  // const { error, success } = await getShopGoodsList({
  //     pid: '0',
  //     nurse_type: modelValue.value,
  //     hospital: props.hospital
  // });
  // success
  // if (!error && success) list.value = success;

  // list.value.forEach(async (item: any) => {
  //     const { error: detailError, success: data } = await loadTreeChildrenNew({ pid: item.key });
  //     if (!detailError && data) item.children = data;
  // });
  // if (list?.value?.length > 0) select.value = list?.value[0].key;

  // list.value
  // hideLoading();
};
watch(
  () => [modelValue.value],
  () => {
    getData();
  }
);
// 暴露验证方法给父组件
defineExpose({
  getData: () => getData()
});
</script>

<style lang="scss">
.pharmacy-container {
  width: 750rpx;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  margin: 0 auto;
  font-size: 12rpx;
  /* 基础字体大小缩放 */


  /* 顶部导航栏 */
  .header {
    background: #2ecc71;
    height: 50rpx;
    display: flex;
    align-items: center;
    padding: 0 12rpx;
    color: white;
  }

  .back-button {
    width: 20rpx;
    height: 20rpx;
    cursor: pointer;
    margin-right: 12rpx;
  }

  .back-button svg {
    width: 100%;
    height: 100%;
  }

  .title {
    font-size: 16rpx;
    font-weight: 500;
    flex: 1;
    text-align: center;
    margin-right: 32rpx;
    /* 平衡左侧按钮的宽度 */
  }

  /* 二级菜单 */
  .category-tabs {
    background: white;
    display: flex;
    padding: 0 12rpx;
    border-bottom: 1px solid #cdcdcd;
    overflow-x: auto;
  }

  .tab-item {
    padding: 12rpx 16rpx;
    font-size: 12rpx;
    color: #666;
    cursor: pointer;
    position: relative;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;
    white-space: nowrap;
    min-width: 80px;
    text-align: center;
  }

  .tab-item.active {
    color: #2ecc71;
    border-bottom-color: #2ecc71;
  }

  .tab-item:hover {
    color: #2ecc71;
  }

  /* 主要内容 */
  .main-content {
    flex: 1;
    display: flex;
    overflow: hidden;
  }

  /* 左侧菜单 */
  .left-sidebar {
    width: 160rpx;
    background: white;
    border-right: 1px solid #f0f0f0;
    overflow-y: auto;
  }

  .sub-category-item {
    padding: 12rpx 16rpx;
    font-size: 12rpx;
    color: #333;
    cursor: pointer;
    border-bottom: 1px solid #f9f9f9;
    transition: all 0.3s ease;
  }

  .sub-category-item.active {
    background: #2ecc71;
    color: white;
    border-radius: 16rpx;
    margin: 3rpx 6rpx;
    border-bottom: none;
  }

  .sub-category-item:hover:not(.active) {
    background: #f8f8f8;
  }

  /* 右侧内容 */
  .right-content {
    flex: 1;
    padding: 16rpx;
    overflow-y: auto;
  }

  .service-header {
    margin-bottom: 20rpx;
  }

  .service-header h3 {
    font-size: 16rpx;
    color: #333;
    margin: 0;
    padding-bottom: 6rpx;
    border-bottom: 2rpx solid #2ecc71;
    display: inline-block;
  }

  /* 商品列表 */
  .product-list {
    /* display: grid; */
    /* grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); */
    /* gap: 16px; */
  }

  .product-item {
    background: white;
    border-radius: 10rpx;
    margin-bottom: 10rpx;
    padding: 16rpx;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .product-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }

  .product-image {
    width: 50rpx;
    height: 50rpx;
    border-radius: 6rpx;
    overflow: hidden;
    flex-shrink: 0;
  }

  .product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .product-info {
    flex: 1;
  }

  .product-brand {
    font-size: 18rpx;
    font-weight: 600;
    color: #2ecc71;
    margin-bottom: 3rpx;
  }

  .product-name {
    font-size: 20rpx;
    color: #666;
    margin-bottom: 6rpx;
    line-height: 1.4;
  }

  .product-price {
    font-size: 18rpx;
    font-weight: 600;
    color: #e74c3c;
  }
}
</style>
